
#include <signal.h>

#include <iostream>

using namespace std;

#include <workflow/WFFacilities.h>
#include <workflow/MySQLMessage.h>
#include <workflow/MySQLResult.h>
#include <workflow/MySQLUtil.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void mysqlCallback(WFMySQLTask * mysqltask)
{
    using namespace protocol;
    cout << "mysqlCallback is running" << endl;
    //错误的检测
    int state = mysqltask->get_state();
    int error = mysqltask->get_error();
    if(state != WFT_STATE_SUCCESS) {
        printf("occurs error: %s\n", WFGlobal::get_error_string(state, error));
        return;
    }
    //语法的检测
    auto resp = mysqltask->get_resp();
    if(resp->get_packet_type() == MYSQL_PACKET_ERROR) {
        printf("ERROR %d, %s\n", resp->get_error_code(),
               resp->get_error_msg().c_str());
        return;
    }
    cout << "111" << endl;

    MySQLResultCursor cursor(resp);
    if(cursor.get_cursor_status() == MYSQL_STATUS_OK) {
        //写操作的处理
        printf("Query OK, %lld row affected. Insert id is %lld\n",
               cursor.get_affected_rows(),
               cursor.get_insert_id());
    } else if(cursor.get_cursor_status() == MYSQL_STATUS_GET_RESULT) {
        //先读取所有的field字段信息
        const MySQLField * const * arr = cursor.fetch_fields();
        for(int i= 0; i < cursor.get_field_count(); ++i) {
            cout << "db:" << arr[i]->get_db() << ", ";
            cout << "table:" << arr[i]->get_table() << ", ";
            cout << "name:" << arr[i]->get_name() << ", ";
            cout << "type:" << datatype2str(arr[i]->get_data_type()) << endl << endl;
        }

        //获取每一行数据
        vector<vector<MySQLCell>> rows;
        cursor.fetch_all(rows);
        for(auto & row : rows) {
            for(auto & cell : row) {
                if(cell.is_int()) {
                    cout << cell.as_int() << " ";
                } else if(cell.is_string()) {
                    cout << cell.as_string() << " ";
                } else if(cell.is_datetime()) {
                    cout << cell.as_datetime();
                }
            }
            cout << "\n";//一行结尾要换行
        }
    }
}

void test0()
{
    signal(SIGINT, sighandler);


    string url("mysql://root:1234@localhost");
    //创建任务
    auto mysqlTask = WFTaskFactory::create_mysql_task(url, 1, mysqlCallback);
    //设置任务的属性
    auto req = mysqlTask->get_req();
    req->set_query("select * from cloudisk.tbl_user_token");

    //交给框架来运行
    mysqlTask->start();

    waitGroup.wait();

}


int main()
{
    test0();
    return 0;
}

